<?php
/**
 * Created by PhpStorm.
 * User: zhanghua
 * Date: 2018/9/19
 * Time: 8:53
 */

namespace app\common\controller;


use think\exception\RouteNotFoundException;
use think\exception\ValidateException;
use think\Loader;
use think\Request;
use think\Response;

class ApiBaseController
{

    /**
     * @var \think\Request Request 实例
     */
    protected $request;

    /**
     * @var bool 验证失败是否抛出异常
     */
    protected $failException = false;

    /**
     * @var bool 是否批量验证
     */
    protected $batchValidate = false;

    /**
     * @var array 前置操作方法列表
     */
    protected $beforeActionList = [];

    /**
     * 返回的格式定义
     * @var string json|jsonp|xml|view
     */
    public $responseType = 'json';

    /**
     * 返回的头信息
     * @var array
     */
    public $responseHeader = [];

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {

        $this->request = is_null($request) ? Request::instance() : $request;

        // 控制器初始化
        $this->_initialize();

        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
            }
        }
    }

    protected function _initialize()
    {
        $action =$this->request->action(true);
        if($action !== 'api'){
            throw new RouteNotFoundException();
        }
    }

    /**
     * 前置操作
     * @access protected
     * @param  string $method  前置操作方法名
     * @param  array  $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
     * @return void
     */
    final protected function beforeAction($method, $options = [])
    {
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }

            if (!in_array($this->request->action(), $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }

            if (in_array($this->request->action(), $options['except'])) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }

    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param bool $fail 是否抛出异常
     * @return $this
     */
    final protected function validateFailException($fail = true)
    {
        $this->failException = $fail;

        return $this;
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @param  mixed        $callback 回调方法（闭包）
     * @return array|string|true
     * @throws ValidateException
     */
    final protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = Loader::validate();
            $v->rule($validate);
        } else {
            // 支持场景
            if (strpos($validate, '.')) {
                list($validate, $scene) = explode('.', $validate);
            }

            $v = Loader::validate($validate);

            !empty($scene) && $v->scene($scene);
        }

        // 批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        // 设置错误信息
        if (is_array($message)) {
            $v->message($message);
        }

        // 使用回调验证
        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            if ($this->failException) {
                throw new ValidateException($v->getError());
            }

            return $v->getError();
        }

        return true;
    }


    /**
     * API的入口
     * @return Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml
     */
    final public function api()
    {
        $api_name = input('api_name');

        if(!$api_name){
            $data = $this->result(404, '接口名称不能为空');
        }else{

            $classReflect = new \ReflectionClass($this);

            if($classReflect->hasMethod($api_name)){

                $methodReflect = $classReflect->getMethod($api_name);

                if($methodReflect->isPublic()){
                    $data = $this->$api_name();
                }else{
                    $data = $this->result(404, '接口不存在');
                }

            }else{
                $data = $this->result(404, '接口不存在');
            }
        }

        $header = $this->responseHeader;
        $type = $this->responseType;
        $options = [];//暂时不知道这个做什么用的
        return Response::create($data, $type, 404, $header, $options);
    }


    /**
     * 返回结果数据
     * @param string $code      结果状态
     * @param string $msg       返回提示
     * @param mixed $data      返回数据
     * @return array
     */
    final protected function result( $code = '', $msg = '', $data = [])
    {
        if(empty($data)) $data = (object) [];

        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];
        return $result;
    }

}